package com.tanhua.dubbo.server.api;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

//生成自增长的id，原理：使用redis的自增长值
@Service
public class IdService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Long createId(String type, String strId) {
        //将publish转为大写
        type = StringUtils.upperCase(type);


        //从redis中获取值,有则直接返回
        String idHashKey = "TANHUA_HASH_ID_" + type;
        if (this.redisTemplate.opsForHash().hasKey(idHashKey, strId)) {
            return Long.valueOf(this.redisTemplate.opsForHash().get(idHashKey, strId).toString());
        }

        //没有则让idKey 的值+1,并获取
        String idKey = "TANHUA_ID_" + type;
        Long id = this.redisTemplate.opsForValue().increment(idKey);

        //将pid保存到redis中
        this.redisTemplate.opsForHash().put(idHashKey, strId, id.toString());

        //返回pid
        return id;
    }

}